import 'dart:io';
import 'dart:ui';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive/hive.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:styled_widget/styled_widget.dart';
import 'package:test2/base/base_page.dart';
import 'package:test2/dialog/move_dialog.dart';
import 'package:test2/item/item_scene.dart';
import 'package:test2/model/scene.dart';
import 'package:test2/util/bus.dart';
import 'package:test2/util/hotkeyUtil.dart';
import 'package:test2/view/scene_add.dart';

import '../style/style.dart';
import '../util/platform.dart';
import '../util/sp.dart';

class SceneList extends StatefulWidget {
  const SceneList({super.key, required this.boxName, required this.mapName});

  final String boxName;
  final String mapName;

  @override
  State<SceneList> createState() => _SceneListState();
}

class _SceneListState extends BaseState<SceneList> {
  late Box<SceneC> box;
  List<SceneC> dataList = [];
  List<SceneC> displayList = [];
  AudioPlayer audioPlayer = AudioPlayer();
  bool edit = false;
  List<int> checkedList = [];

  @override
  void initState() {
    init();
    initHotkey();
    bus.on(EventType.scene, onDataChange);
    super.initState();
  }

  onDataChange(arg) {
    updateList();
  }

  final HotKey _hotKey = HotKey(
    key: HotKeyUtil.getNewKey(),
    modifiers: [HotKeyModifier.alt],
    scope: HotKeyScope.system,
  );

  initHotkey() async {
    if (!PlatformUtil.isDesktop()) {
      return;
    }

    await hotKeyManager.register(
      _hotKey,
      keyDownHandler: (hotKey) async {
        if (ModalRoute.of(context)?.isCurrent ?? false) {
          audioPlayer.play(AssetSource("mp3/new.mp3"));
          addData();
        }
      },
    );
  }

  @override
  void dispose() {
    bus.off(EventType.scene, onDataChange);
    box.close();
    if (PlatformUtil.isDesktop()) {
      hotKeyManager.unregister(_hotKey);
    }
    super.dispose();
  }

  List<String> tags = ["全部", "无", ...defaultTags];
  String? tag = null;

  void init() async {
    box = await Hive.openBox<SceneC>(widget.boxName);
    tags.addAll(SpUtil.get().getStringList("tags") ?? []);
    setState(() {
      tags;
      selectTab = SpUtil.get().getInt("scenetab") ?? 0;
    });
    updateList();
  }

  void updateList() {
    setState(() {
      dataList.clear();
      dataList.addAll(box.values);
      dataList = dataList.reversed.toList();

      // 置顶
      final doneList = dataList.where((item) => item.done).toList();
      final todoList = dataList.where((item) => !item.done).toList();

      dataList = [...todoList, ...doneList];

      displayList = filterList();
    });
  }

  int selectTab = 0;
  List<String> tabs = ["默认", "位置特写", "场景特写"];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.mapName),
        actions: [
          TextButton(
            onPressed: () {
              setState(() {
                edit = !edit;
                checkedList.clear();
              });
            },
            child: Text(edit ? "取消" : "移动"),
          ).padding(right: 8),
        ],
      ),
      floatingActionButton: edit
          ? null
          : FloatingActionButton(
              onPressed: () {
                addData();
              },
              child: Icon(Icons.add),
            ),
      body: SizedBox.expand(
        child: Column(
          children: [
            Padding(
              padding: EdgeInsetsGeometry.symmetric(
                vertical: 4,
                horizontal: 16,
              ),
              child: Row(
                children: [
                  Row(
                    children: List.generate(tabs.length, (index) {
                      return TextButton(
                        onPressed: () {
                          setState(() {
                            selectTab = index;
                            SpUtil.get().setInt("scenetab", selectTab);
                          });
                        },
                        child: Text(
                          tabs[index],
                          style: TextStyle(
                            color: (selectTab == index)
                                ? Theme.of(context).primaryColor
                                : Colors.grey,
                          ),
                        ),
                      );
                    }),
                  ),

                  Spacer(),

                  SizedBox(
                    height: 30,
                    child: DropdownButton<String>(
                      underline: SizedBox(),
                      style: TextStyle(fontSize: 14, color: Colors.black),
                      hint: Text("标签选择", style: TextStyle(fontSize: 14)),
                      value: tag,
                      onChanged: (String? newValue) {
                        setState(() {
                          tag = newValue;
                          displayList = filterList();
                        });
                      },
                      items: tags.map<DropdownMenuItem<String>>((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: ListView.separated(
                padding: EdgeInsets.only(
                  left: 16,
                  right: 16,
                  top: 16,
                  bottom: 100,
                ),
                itemBuilder: (context, index) {
                  var item = displayList[index];
                  return GestureDetector(
                    onTap: () {
                      itemClick(item);
                    },
                    child: Row(
                      spacing: 4,
                      children: [
                        if (edit)
                          Checkbox(
                            value: checkedList.contains(index),
                            onChanged: (check) {
                              // print(check);
                              setState(() {
                                if (check ?? false) {
                                  checkedList.add(index);
                                } else {
                                  checkedList.remove(index);
                                }
                              });
                            },
                          ),
                        Expanded(
                          child: ItemScene(
                            data: item,
                            boxName: widget.boxName,
                            showMode: selectTab + 1,
                          ),
                        ),
                      ],
                    ),
                  );
                },
                separatorBuilder: (context, index) {
                  return SizedBox(height: 12);
                },
                itemCount: displayList.length,
              ),
            ),
            if (edit)
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton(
                  onPressed: () {
                    move();
                  },
                  child: Text("确认移动"),
                ),
              ),
          ],
        ),
      ),
    );
  }

  void move() async {
    if (checkedList.isEmpty) {
      showToast("请选择一项");
      return;
    }

    List<SceneC> select = [];
    for (var index in checkedList) {
      select.add(displayList[index]);
    }

    bool? res = await showDialog<bool>(
      context: context,
      builder: (_) {
        return AlertDialog(
          // scrollable: true,
          title: Text("选择地图"),
          content: MoveDialog(boxName: widget.boxName, list: select),
        );
      },
    );

    if (res ?? false) {
      setState(() {
        edit = false;
        checkedList.clear();
      });
    }
  }

  void itemClick(SceneC item) {
    startPage(SceneAdd(boxName: widget.boxName, info: item));
  }

  void addData() {
    startPage(SceneAdd(boxName: widget.boxName));
  }

  List<SceneC> filterList() {
    if (tag == null || tag == "全部") {
      return dataList;
    }
    if (tag == "无") {
      return dataList.where((item) => item.tag.isEmpty).toList();
    }
    return dataList.where((item) => item.tag == tag).toList();
  }
}
